package com.banzhi.shop.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.banzhi.shop.R;
import com.banzhi.shop.adapter.OrderManagementAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.OrderAffirm.OrderAffirm;
import com.banzhi.shop.entity.OrderManagement.Order_Data;
import com.banzhi.shop.entity.RefundRequest.Refund_Data;
import com.banzhi.shop.model.CallBack.DeleteOrderCallBack;
import com.banzhi.shop.model.CallBack.FindGoodsCallBack;
import com.banzhi.shop.model.CallBack.OrdersManagementCallBack;
import com.banzhi.shop.model.CallBack.RefundRequestCallBack;
import com.banzhi.shop.model.IDeleteOrderModel;
import com.banzhi.shop.model.IFindGoodsModel;
import com.banzhi.shop.model.IOrderManagementModel;
import com.banzhi.shop.model.IRefundRequestModel;
import com.banzhi.shop.model.Impl.DeleteOrderImpl;
import com.banzhi.shop.model.Impl.FindGoodsImpl;
import com.banzhi.shop.model.Impl.OrderManagementImpl;
import com.banzhi.shop.model.Impl.RefundRequestImpl;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.banzhi.shop.R.id.srlayout;
import static com.loopj.android.http.AsyncHttpClient.log;
//订单搜索
public class FindOrderActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener, OrdersManagementCallBack, RefundRequestCallBack, FindGoodsCallBack, DeleteOrderCallBack {
    /**
     * 退出
     */
    private ImageView ivback;
    /**
     * 列表
     */
    private ListView listView;
    /**
     * 下拉刷新
     */
    private SwipeRefreshLayout srllistview;
    /**
     * 判断listview是不是滑到最低端了
     */
    private boolean isbottom;
    private int page = 1;
    private RelativeLayout rlnodata;
    private IOrderManagementModel model;
    private List<Order_Data> orderdata = new ArrayList<>();
    private OrderManagementAdapter adapter;
    private int position;
    /**
     * 申请退款的接口
     */
    private IRefundRequestModel requestModel;
    private EditText etfind;
    private IFindGoodsModel findGoodsModel;
    private IDeleteOrderModel deleteOrderModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_order);
        Translucent.setTranslucent(this);
        setinits();
        setListeners();
        model = new OrderManagementImpl();
        requestModel = new RefundRequestImpl();
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        model.getOrderData("-1", page, this);
        findGoodsModel = new FindGoodsImpl();
        deleteOrderModel = new DeleteOrderImpl();
    }

    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        srllistview = (SwipeRefreshLayout) findViewById(srlayout);
        listView = (ListView) findViewById(R.id.listview);
        srllistview.setColorSchemeResources(R.color.themeColor);
        srllistview.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        srllistview.setOnRefreshListener(this);
        rlnodata = (RelativeLayout) findViewById(R.id.rl_nodata);
        etfind = (EditText) findViewById(R.id.et_find);
    }

    private void setListeners() {
        ivback.setOnClickListener(this);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && isbottom) {
                    page++;
                    if (etfind.getText().length() == 0) {
                        LoadingDialogUtils.showProgress(FindOrderActivity.this, "正在加载,请稍后~");
                        model.getOrderData("-1", page, FindOrderActivity.this);
                    } else {
                        LoadingDialogUtils.showProgress(FindOrderActivity.this, "正在加载,请稍后~");
                        findGoodsModel.findgoods(etfind.getText().toString().trim(), page, FindOrderActivity.this);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    isbottom = true;
                } else {
                    isbottom = false;
                }
            }
        });
        etfind.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    page = 1;
                    findGoodsModel.findgoods(etfind.getText().toString().trim(), page, FindOrderActivity.this);
                } else {
                    model.getOrderData("-1", page, FindOrderActivity.this);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
     * 展示列表
     */
    private void ShowData() {
        if (adapter == null) {
            adapter = new OrderManagementAdapter(FindOrderActivity.this, orderdata);
            listView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        adapter.getcallback(new OrderManagementAdapter.zhifuCallBack() {
            @Override
            public void zhifu(String id, int position) {
                LoadingDialogUtils.showProgress(FindOrderActivity.this, "正在加载,请稍后~");
                model.zhifu(id, FindOrderActivity.this);
                FindOrderActivity.this.position = position;
            }

            @Override
            public void delete(String id, int position) {
                LoadingDialogUtils.showProgress(FindOrderActivity.this, "正在加载,请稍后~");
                model.delete(id, FindOrderActivity.this);
                FindOrderActivity.this.position = position;
            }

            @Override
            public void queren(String id, int position) {
                LoadingDialogUtils.showProgress(FindOrderActivity.this, "正在加载,请稍后~");
                model.shouhuo(id, FindOrderActivity.this);
                FindOrderActivity.this.position = position;
            }

            @Override
            public void tuikuan(String id, int position) {
                LoadingDialogUtils.showProgress(FindOrderActivity.this, "正在加载,请稍后~");
                requestModel.getData(id, FindOrderActivity.this);
                FindOrderActivity.this.position = position;
            }

            @Override
            public void deleteorder(String id, int position) {
                LoadingDialogUtils.showProgress(FindOrderActivity.this, "正在加载,请稍后~");
                deleteOrderModel.deleteOrder(id, FindOrderActivity.this);
                FindOrderActivity.this.position = position;
            }
        });

    }

    /**
     * @param object 获取订单信息成功
     */
    @Override
    public void ongetDataSuccess(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        LoadingDialogUtils.dismiss();
        if (page == 1) {
            orderdata.clear();
        } else {
            if (((List<Order_Data>) object).size() == 0) {
//                ToastUtils.makeToastShort("没有更多了");
                return;
            }
        }
        orderdata.addAll((List<Order_Data>) object);
        log.d("orderdata", orderdata.toString());
        if (orderdata.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }

        ShowData();

    }


    /**
     * @param object 获取订单信息失败
     */
    @Override
    public void ongetDataError(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(FindOrderActivity.this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 支付成功
     */
    @Override
    public void zhifuSuccess(Object object) {
        LoadingDialogUtils.dismiss();
        OrderAffirm data = (OrderAffirm) object;
        Intent intent = new Intent(FindOrderActivity.this, CheckstandActivity.class);
        intent.putExtra("orderid", orderdata.get(position).getId());
        intent.putExtra("goodprice", data.getRes().getOrderInfo().getGoodsprice());
        intent.putExtra("balance", data.getRes().getBalance());
        intent.putExtra("bianma", data.getRes().getOrderInfo().getOrdersn());
        startActivity(intent);
        finish();
    }

    /**
     * @param object 支付失败
     */
    @Override
    public void zhifuError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(FindOrderActivity.this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 取消订单成功
     */
    @Override
    public void deleteOrderSuccess(Object object) {
        orderdata.remove(position);
        if (orderdata.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        adapter.notifyDataSetChanged();
        ToastUtils.makeToastShort("取消订单成功");
    }

    /**
     * @param object 取消订单失败
     */
    @Override
    public void deleteOrderError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 确认收货成功
     */
    @Override
    public void querenOrderSuccess(Object object) {
        orderdata.remove(position);
        if (orderdata.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * @param object 确认收货失败
     */
    @Override
    public void querenOrderError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void onRefresh() {
        page = 1;
        if (etfind.getText().length() == 0) {
            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
            model.getOrderData("-1", page, this);
        } else {
            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
            findGoodsModel.findgoods(etfind.getText().toString().trim(), page, FindOrderActivity.this);
        }
    }

    /**
     * 申请退款成功
     *
     * @param object
     */
    @Override
    public void onrefundrequestSuccess(Object object) {
        Refund_Data refund = (Refund_Data) object;
        Intent RRintent = new Intent(this, RefundRequestActivity.class);
        RRintent.putExtra("data", refund);
        startActivity(RRintent);
    }

    /**
     * 申请退款失败
     *
     * @param object
     */
    @Override
    public void onrefundrequestError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * 删除订单成功
     *
     * @param object
     */
    @Override
    public void deleteSuccess(Object object) {
        orderdata.remove(position);
        if (orderdata.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        adapter.notifyDataSetChanged();
        ToastUtils.makeToastShort("删除订单成功");
    }

    /**
     * 删除订单失败
     *
     * @param object
     */
    @Override
    public void deleteError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
}
